package com.zhaojonhy.zhaopangwb.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;

import com.zhaojonhy.zhaopangwb.R;

/**
 * Created by Administrator on 2016/10/17.
 */

public class UnderlineFor3 extends LinearLayout {

    private int mCurrentPosition;

    public UnderlineFor3(Context context) {
        super(context);
    }

    public UnderlineFor3(Context context, AttributeSet attrs) {
        super(context, attrs);

        setOrientation(HORIZONTAL);
        int count = 3 ;
        for(int i = 0 ; i < count ; i++ ){ //逐个设置3个参数
            View view = new View(context) ;
            LayoutParams params = new LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT) ;
            params.weight = 1 ;
            view.setLayoutParams(params);
            view.setBackgroundResource(R.color.transparent);
            addView(view);
        }
    }

    //隐藏的部分无动画选中
    public void setCurrentItemWithoutAnim(int position){
        final View oldChild = getChildAt(mCurrentPosition) ; //当前视图
        final View newChild = getChildAt(position) ; //目标视图

        oldChild.setBackgroundResource(R.color.transparent) ;
        newChild.setBackgroundResource(R.color.orange) ;
        mCurrentPosition = position ; //记录当前位置
        invalidate(); //由于视图引起变化，进行页面的更新

    }

    //显示的部分有动画选中
    public void setCurrentItem(int position){ //选中状态，从原有的状态跳到当前状态
        final View oldChild = getChildAt(mCurrentPosition) ; //当前视图
        final View newChild = getChildAt(position) ; //目标视图

        TranslateAnimation translateAnimation = new TranslateAnimation( // X 轴相对自己全体位移，Y 轴不变
                Animation.RELATIVE_TO_SELF,0,
                Animation.RELATIVE_TO_SELF,position - mCurrentPosition,
                0,0,0,0) ;
        translateAnimation.setDuration(200);
        translateAnimation.setAnimationListener(new Animation.AnimationListener() { //位移监听动画，也就是效果
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) { //动画结束
                oldChild.setBackgroundResource(R.color.transparent) ;
                newChild.setBackgroundResource(R.color.orange) ;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        oldChild.setAnimation(translateAnimation); //执行动画
        mCurrentPosition = position ; //记录当前位置

        invalidate(); //由于视图引起变化，进行页面的更新

    }
}
